package com.dtflys.easyel.runtime;

import com.dtflys.easyel.utils.MetaHelper;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @author gongjun[jun.gong@thebeastshop.com]
 * @since v1.0.0
 */
public class InvokableMetaMethod extends MetaMethod {

    private final static Object[] EMPTY_ARGUMENTS = new Object[0];
    private final Method method;


    public InvokableMetaMethod(Method method) {
        this(method.getName(), method);
    }

    public InvokableMetaMethod(String methodName, Method method) {
        super(methodName, method.getParameterTypes(), method.isVarArgs());
        this.method = method;
    }

    public Method getMethod() {
        return method;
    }

    public Object invokeWithEmptyArguments(Object self) throws InvocationTargetException, IllegalAccessException {
        return invoke(self, EMPTY_ARGUMENTS);
    }

//    @Override
    public Object invoke(Object self, Object[] arguments) throws InvocationTargetException, IllegalAccessException {
        Object[] castedArgs = MetaHelper.castArguments(getParamTypes(), arguments);
        Object result = method.invoke(self, castedArgs);
        return MetaHelper.wrap(result);
    }


}
